//
//  CoinDetailViewController.m
//  TenMinDemo
//
//  Created by Shawn Li on 2021/3/8.
//  Copyright © 2021 CYXiang. All rights reserved.
//

#import "CoinDetailViewController.h"
#import "CoinExchangeRecordTableCell.h"
#import "DateTabHeader.h"
#import "MaskTabFooter.h"
#import "TransferOutViewController.h"
#import "TransferInViewController.h"
#import "TransferDetailViewController.h"
#import <UIImageView+WebCache.h>
#import "CYXBaseRequest.h"
#import "TransferLogModel.h"
#import "CoinItemModel.h"
#import "DateTool.h"


@interface CoinDetailViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIImageView *icon;
@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UILabel *info;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *tsfInBtn;
@property (weak, nonatomic) IBOutlet UIButton *tsfOutBtn;
/// <#注释#>
@property (nonatomic, assign) NSInteger page;

/// <#注释#>
@property (nonatomic, strong) NSMutableArray *logMList;

/// <#注释#>
@property (nonatomic, strong) CoinItemModel *coinDM;
@end

@implementation CoinDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.logMList = [NSMutableArray array];
    [self loadNewData];
    [self getCoinDetail];
    
}

- (void)setupUI{
    [super setupUI];
    self.tableView.backgroundColor = [UIColor colorWithRed:(23.0)/255 green:(25.0)/255 blue:(29.0)/255 alpha:1];
    self.tableView.isNeedEmpty = @"1";
    //    MaskTabFooter *t = [[MaskTabFooter alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 30, 10)];
    //    self.tableView.tableFooterView = t;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"CoinExchangeRecordTableCell" bundle:nil] forCellReuseIdentifier:@"CoinExchangeRecordTableCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DateTabHeader" bundle:nil] forHeaderFooterViewReuseIdentifier:@"DateTabHeader"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MaskTabFooter" bundle:nil] forHeaderFooterViewReuseIdentifier:@"MaskTabFooter"];
    
    [self.icon sd_setImageWithURL:[NSURL URLWithString:self.coinM.iconUrl]];
    self.name.text = self.coinM.name;
    self.info.text = [NSString stringWithFormat:@"%lf",self.coinM.balance];
    [self.tsfInBtn setTitle:LCLocalString(@"transfer_in") forState:(UIControlStateNormal)];
    [self.tsfOutBtn setTitle:LCLocalString(@"transfer_out") forState:(UIControlStateNormal)];
    
    
    [self tableView:self.tableView refreshAction:@selector(loadNewData) loadMoreAction:@selector(loadMoreData)];
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.logMList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    TransferLogModel *tsfM = self.logMList[section];
    return tsfM.basicViewList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TransferLogModel *tsfM = self.logMList[indexPath.section];
    TransferLogItem *tsfItem = tsfM.basicViewList[indexPath.row];
    
    CoinExchangeRecordTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CoinExchangeRecordTableCell"];
    [cell refreshModel:tsfItem];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //    if (section == 0) {
    return 50.0f;
    //    }
    //    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    TransferLogModel *tsfM = self.logMList[section];
    DateTabHeader *h = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"DateTabHeader"];
    h.isRadius = (section == 0);
    h.title.text = [DateTool yearDateStrWithTime:tsfM.date];
    [h refresh];
    
    return h;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (!self.logMList.count) {
        return CGFLOAT_MIN;
    }
    if (section == self.logMList.count - 1) {
        return 10;
    }
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    MaskTabFooter *f = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MaskTabFooter"];
    return f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TransferLogModel *tsfM = self.logMList[indexPath.section];
    TransferLogItem *tsfItem = tsfM.basicViewList[indexPath.row];
    TransferDetailViewController *vc = [[TransferDetailViewController alloc] init];
    vc.tsfId = tsfItem.id;
    vc.tsfType = tsfItem.type;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (IBAction)transferInAction:(id)sender {
    if (!self.coinDM) {
        return;
    }
    if (!self.coinDM.canTransfer) {
        LCInfoHUD(LCLocalString(@"not_spt"), 1.5);
        return;
    }
    
    TransferInViewController *vc = LoadVCFormXib(TransferInViewController);
    vc.coinM = self.coinM;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (IBAction)transferOutAction:(id)sender {
    if (!self.coinDM) {
        return;
    }
    if (!self.coinDM.canTransfer) {
        LCInfoHUD(LCLocalString(@"not_spt"), 1.5);
        return;
    }
    TransferOutViewController *vc = LoadVCFormXib(TransferOutViewController);
    vc.coinM = self.coinM;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark-

- (void)loadNewData{
    self.page = 1;
    [self getTsfLog_net];
}

- (void)loadMoreData{
    [self getTsfLog_net];
}

- (void)getTsfLog_net{
    NSDictionary *param = @{@"pageNo":@(self.page),@"assetId":@(self.coinM.id)};
    [CYXBaseRequest postWithUrl:API_getTsfLoglist param:param resultClass:nil success:^(id res) {
        if ([res isEqual: RequestErrorCode]) {
            
        }else{
            NSArray *logArr = [TransferLogModel mj_objectArrayWithKeyValuesArray:res[@"list"]];
            NSDictionary *pageInfo = res[@"page"];
            if (self.page == 1) {
                self.logMList = [NSMutableArray arrayWithArray:logArr];
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer resetNoMoreData];
                //                刷新了
            }else{
                [self mergeModel:logArr];
                [self.tableView.mj_footer endRefreshing];
            }
            
            
            NSInteger totalPage = [pageInfo[@"totalPages"] integerValue];
            if (self.page == totalPage) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.page++;
            }
            
            [self.tableView reloadData];
        }
        
        CYXLog(@"%@",res)
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
}

// 由于分页的原因可能数据需要合并
- (void)mergeModel:(NSArray *)newMList{
    if (!newMList.count) {
        return;
    }
    TransferLogModel *lastOldM = self.logMList.lastObject;
    TransferLogModel *firstNewM = newMList.firstObject;
    
    if (lastOldM.date == firstNewM.date) { // 是同一天需要合并
        NSMutableArray *newTempList = [NSMutableArray arrayWithArray:newMList];
        
        NSMutableArray *logList = [NSMutableArray arrayWithArray:lastOldM.basicViewList];
        [logList addObjectsFromArray:firstNewM.basicViewList];
        lastOldM.basicViewList = logList;
        
        [newTempList removeObject:newTempList.firstObject];
        
        [self.logMList addObjectsFromArray:newTempList];
        
    }else{
        [self.logMList addObjectsFromArray:newMList];
    }
    
    
}


- (void)getCoinDetail{
    NSDictionary *param = @{@"assetId":@(self.coinM.id)};
    
    [CYXBaseRequest postWithUrl:API_getAssetDetail param:param resultClass:[CoinItemModel class] success:^(id res) {
        if ([res isEqual: RequestErrorCode]) {
            
        }else{
            self.coinDM = res;
        }
        
        CYXLog(@"%@",res)
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
}



@end
